import Vue from 'vue'
import Vuex from 'vuex'
import electron from 'electron'
import C from './common.js'
Vue.use(Vuex)
const store = new Vuex.Store()
/*
 * store类
 * 黄总
 * 2018.1.15
 */
class S {
    /*
   * 设置当前页面store
   * model: 模块
   */
    setStore (model, data) {
    // 首先判断当前文件是否加载自动提交函数
        this.registerStore(model)
        console.log(store)
        store.commit(model + '/_setStore', data)
    }

    /*
   * 分发全局store
   */
    setGlobalStore (model, data) {
    // 分发store
        electron.ipcRenderer.send('_setGlobalStore', {model: model, data: data})
    }

    /*
   * 接收全局store
   */
    getGlobalStore () {
        electron.remote.ipcMain.on('_setGlobalStore', (event, arg) => {
            this.setStore(arg.model, arg.data)
        })
    }

    /*
   * 设置长期存储store
   */
    setStorageStore (model, data) {
        let storeStorage = C.getLocalStorage('_storeStorage') || {}
        let _data = {}
        _data[model] = data
        storeStorage = Object.assign(storeStorage, _data)
        C.setLocalStorage('_storeStorage', storeStorage)
        this.setGlobalStore(model, data)
    }

    /*
   * 获取长期存储的store
   */
    getStorageStore () {
    // 暂时加载所有storage到store
        let storeStorage = C.getLocalStorage('_storeStorage') || {}
        for (let model in storeStorage) {
            if (storeStorage[model]) {
                this.setStore(model, storeStorage[model])
            }
        }
    }

    /*
   * store初始化
   */
    init () {
        this.getStorageStore()
        this.getGlobalStore()
    }

    /*
   * 注册动态函数
   */
    registerStore (model) {
        let mutationsName = model + '/_setStore'
        if (!store._mutations[mutationsName]) {
            let obj = {}
            obj[mutationsName] = (state, obj) => {
                for (let key in obj) {
                    if (state) state[key] = obj[key]
                }
            }
            store.registerModule(model, {
                mutations: obj
            }, { preserveState: true })
        }
    }
}

export default new S()
